package redecolaborativa.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratedTabBar;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;

public class HistoricoAtividades extends Composite {
	ScrollPanel scrollPanel = new ScrollPanel();
	
	public HistoricoAtividades(final FachadaAsync fachada, final String idSessao) {
		AbsolutePanel absolutePanel = new AbsolutePanel();
		initWidget(absolutePanel);
		absolutePanel.setSize("615px", "432px");
		
		final DecoratedTabBar decoratedTabBar = new DecoratedTabBar();
		absolutePanel.add(decoratedTabBar, 10, 10);
		decoratedTabBar.setSize("592px", "26px");
		decoratedTabBar.addTab("Suas atualizacoes");
		decoratedTabBar.addTab("Voce e seus amigos");		
		
		absolutePanel.add(scrollPanel, 20, 48);
		scrollPanel.setSize("582px", "374px");
		
		decoratedTabBar.addSelectionHandler(new SelectionHandler<Integer>() {
			public void onSelection(SelectionEvent<Integer> event) {
				if(decoratedTabBar.getSelectedTab() == 0) {
					fachada.historicoIndividual(idSessao, new AsyncCallback<String>() {
						@Override
						public void onSuccess(String result) {
							mostraHistorico(result);
						}
						@Override
						public void onFailure(Throwable caught) {
							Window.alert(caught.getMessage());
						}
					});
				} else if(decoratedTabBar.getSelectedTab() == 1) {
					fachada.historicoConjunto(idSessao, new AsyncCallback<String>() {
						@Override
						public void onSuccess(String result) {
							mostraHistorico(result);
						}
						@Override
						public void onFailure(Throwable caught) {
							Window.alert(caught.getMessage());
						}
					});
				}
			}
		});
	}
	
	private void mostraHistorico(String historico) {
		AbsolutePanel panel = new AbsolutePanel();
		Label atividade;
		for(String str : formataHistorico(historico)) {
			atividade = new Label(str);
			panel.add(atividade);
		} 
		scrollPanel.clear();
		scrollPanel.add(panel);
	}
	
	private List<String> formataHistorico(String historico) {
		List<String> retorno = new ArrayList<String>();
		if(historico.contains(";")) {
			String[] historicoSpl = historico.split("; ");
			for (int i = 0; i < historicoSpl.length; i++) {
				retorno.add(historicoSpl[i]);
			}
		} else {
			retorno.add(historico);
		} return retorno;
	}
}
